package top.huntwolf.admin.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import top.huntwolf.admin.pojo.shop.ShopContext;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.regex.Pattern;


@Intercepts(
        @Signature(type = StatementHandler.class,
                method = "prepare",
                args = {Connection.class,Integer.class}))
public class MybatisSqlInterceptor implements Interceptor {

    private static final Pattern SHOP_PATTERN = Pattern.compile("@storeId@");

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler handler = (StatementHandler) invocation.getTarget();
        BoundSql boundSql = handler.getBoundSql();
        String sql = boundSql.getSql();
        if (ShopContext.get()==null){
            return invocation.proceed();
        }
        sql = SHOP_PATTERN.matcher(sql).replaceAll(ShopContext.get().toString());
        Field sqlField = boundSql.getClass().getDeclaredField("sql");
        sqlField.setAccessible(true);
        sqlField.set(boundSql, sql);
        return invocation.proceed();
    }
}